export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let oldScrollTop = document.documentElement.scrollTop
  callback = callback || function() {}
  window.addEventListener(
    'scroll',
    event => {
      throttle(() => {
        let scrollType = 'up'
        const newScrollTop = event.target.scrollTop || document.documentElement.scrollTop
        const delta = newScrollTop - oldScrollTop
        if (delta === 0) {
          return false
        }
        scrollType = delta > 0 ? 'down' : 'up'
        callback({
          type: scrollType,
          scrollTop: newScrollTop, // 距离顶部的距离
          clientHeight: document.documentElement.clientHeight, // 可视区的高度
          scrollHeight: document.documentElement.scrollHeight // 滚动条的总高度
        })
        oldScrollTop = newScrollTop
      }, 100)
    },
    false
  )
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

export function millsToTime(mills) {
  if (!mills) {
    return ''
  }
  const s = mills / 1000
  if (s < 60) {
    return s.toFixed(0) + ' 秒'
  }
  const m = s / 60
  if (m < 60) {
    return m.toFixed(0) + ' 分钟'
  }
  const h = m / 60
  if (h < 24) {
    return h.toFixed(0) + ' 小时'
  }
  const d = h / 24
  if (d < 30) {
    return d.toFixed(0) + ' 天'
  }
  const month = d / 30
  if (month < 12) {
    return month.toFixed(0) + ' 个月'
  }
  const year = month / 12
  return year.toFixed(0) + ' 年'
}

//生成小程序链接
export function getLink(path, query) {
  let link = `pages/base/startPage/main?path=${path}`
  query && (link += `&query=${JSON.stringify(query)}`)
  return link
}

/**
 * 防抖函数
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 */
let timeout = null
export function debounce(func, wait = 1000, immediate = true) {
  // 清除定时器
  if (timeout !== null) clearTimeout(timeout)
  // 立即执行，此类情况一般用不到
  if (immediate) {
    const callNow = !timeout
    timeout = setTimeout(() => {
      timeout = null
    }, wait)
    if (callNow) typeof func === 'function' && func()
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    timeout = setTimeout(() => {
      typeof func === 'function' && func()
    }, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 */
let timer = null
let flag = null
export function throttle(func, wait = 1000, immediate = true) {
  if (immediate) {
    if (!flag) {
      flag = true
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === 'function' && func()
      timer = setTimeout(() => {
        flag = false
      }, wait)
    }
  } else if (!flag) {
    flag = true
    // 如果是非立即执行，则在wait毫秒内的结束处执行
    timer = setTimeout(() => {
      flag = false
      typeof func === 'function' && func()
    }, wait)
  }
}

// 获取路径名称 suffix 是否需要后缀
export function getFilename(url, suffix = true) {
  url = url.replace(/(\?|#)[^'"]*/, '')
  let filename = url.substring(url.lastIndexOf('/') + 1)
  return suffix ? filename : filename.substring(0, filename.lastIndexOf('.'))
}

// 封面图图片后缀拼接
export function getImagePathSmall(url) {
  url = url.replace(/(\?|#)[^'"]*/, '')
  return url + '?x-image-process=image/resize,w_1000,h_1200/quality,q_50'
}

// 获取自定义列表当前table在缓存的唯一key
export function getColumnsKey(suffix) {
  const tenantId = localStorage.getItem('tenantId')
  const routerName = getFilename(window.location.pathname)

  console.log(`${tenantId}-${routerName}-${suffix}`)
}

/**
 * @description 判断是否是JSON
 * @date 23/05/2024
 * @export
 */
export function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str)
      if (typeof obj == 'object' && obj) {
        return true
      } else {
        return false
      }
    } catch (e) {
      // console.log('error：' + str + '!!!' + e)
      return false
    }
  } else {
    // console.log('It is not a string!')
    return false
  }
}
